var DBFactory = require('../db/mysql_db');
var async = require('async');
var API = require('../libs/wxpay/WxPayApi');
var PayData = require('../libs/wxpay/WxPayDatabak.js');
var paymentDao = module.exports;

paymentDao.getJSAPIPay = function(data, cb) {
    var input = new PayData.WxPayDataBase();
    var out_trade_no = data.orderInfo.order_code;
    var total_fee = parseInt(data.orderInfo.pay_amount * 100);
    // var total_fee = 1;
    var body = data.orderInfo.name;
    var payApi = new API.WxPayApi();
    input.SetBody(body);                                                   //商品描述
    input.SetAttach(data.orderInfo.name);                                  //附加信息
    input.SetOut_trade_no(out_trade_no);                                   //订单号
    input.SetTotal_fee(total_fee);                                         //价格  单位分
    // input.SetNotify_url("http://sk92cm.natappfree.cc/qrcode/notify");   //回调地址
    input.SetSpbill_create_ip('127.0.0.1');                                //终端ip
    input.SetTrade_type("JSAPI");
    input.SetOpenid(data.openid);
    input.SetProduct_id(data.orderInfo.name);                              //商品id   native  必传
    input.SetKeys();
    // var ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
    var ip = '127.0.0.1';
    payApi.unifiedOrder(input, 6, ip, function(result) {
        if(result) {
            result = input.Init(result);
            if(result.return_code == 'SUCCESS') {
                var obj = {nonceStr: result.nonce_str, package:'prepay_id='+ result.prepay_id, timeStamp: new Date().getTime().toString()};
                var paySign = input.MakePaySign(obj);
                obj.paySign = paySign;
                cb(null, obj);
            } else {
                cb('订单生成失败， 请重试！');
            }
        } else {
            cb('参数有误！');
        }
    });
}

function getOrderCode() {
    var now = new Date();
    var code = '13' + now.getFullYear() + parseInt(now.getMonth() + 1) + now.getDate() + now.getHours() + now.getMinutes() + Math.floor(Math.random()*10) + Math.floor(Math.random()*10) + now.getSeconds();
    return code + '3040';
}
function doSaveOrder(orderInfo, cb) {
    var sql = 'insert into order_list set ? ';
    DBFactory.executeSql(sql, orderInfo, 'doSaveOrder', function(err, result) {
        if(err) return cb(err);
        cb(null, orderInfo);
    })
}
paymentDao.createOrder = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'select * from purchase_item where id = ? and status  = 1 ';
    DBFactory.executeSql(sql, [data.item_id], 'getVipInfo', function(err, result) {
        if(err) return cb(err);
        if(result.length == 0) return cb('暂无该购买项，请重试！');
        var orderInfo = {};
        orderInfo.item_id = data.item_id;
        orderInfo.order_code = getOrderCode();
        orderInfo.openid = data.openid;
        orderInfo.name = result[0].name;
        orderInfo.lvl = result[0].lvl;
        orderInfo.duration = result[0].duration;
        orderInfo.price = result[0].price;
        orderInfo.num = data.num;
        if(data.comment) orderInfo.comment = data.comment;
        orderInfo.pay_amount = parseInt(data.num) * parseFloat(result[0].price);
        doSaveOrder(orderInfo, cb);
    })
}

function getOrderInfo(data, connection, callback) {
    var sql = 'select * from order_list where order_code = ? ';
    connection.query(sql, [data.out_trade_no], function(err, result) {
        if(err) return callback(err);
        if(result.length == 0 ) return callback('无该订单信息！');
        data.orderInfo = result[0];
        callback(null, data);
    });
}
function updateMechanism(data, connection, callback) {
    var sql = 'update mechanism set status = 1 where openid = ? ';
    connection.query(sql, [data.orderInfo.openid], function(err) {
        if(err) return callback(err);
        callback(null, data);
    });
}
function updateOrderStatus (data, connection, callback) {
    var sql = 'update order_list set  status = ?, pay_time = NOW() , payment = ?, pay_type = ? where order_code = ? ';
    connection.query(sql, [data.status, data.payment, data.pay_type, data.out_trade_no], function(err) {
        callback(err, data);
    });
}
function addAuth(data, connection, callback) {
    var auth = [];
    auth.push(data.orderInfo.openid);
    auth.push(data.orderInfo.duration);
    auth.push(0);
    auth.push(0);
    auth.push(0);
    auth.push(0);
    var auths = [];
    for(var i=1; i<=data.orderInfo.num; i++) auths.push(auth);
    var sql = 'insert into auth(`openid`,`duration`,`course_id`,`mechanism_id`,`is_used`,`mp_id`) values ? ';
    connection.query(sql, [ auths ], function(err){
        callback(err, data);
    });
}
function log(data, connection, callback) {
    var log = {};
    log.pi_id = data.orderInfo.item_id;
    log.type = 0;
    log.cost = data.orderInfo.pay_amount;
    log.duration = data.orderInfo.duration;
    log.openid = data.orderInfo.openid;
    log.num = data.orderInfo.num;
    var sql = 'insert into purchase_log set ? ';
    connection.query(sql, log, function(err){
        callback(err, data);
    });
}

paymentDao.tradeSuccess = function(data, cb) {
    if(!data) return cb(new ERR(500));
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
        } else {
            async.waterfall([
                function (callback) {
                    connection.beginTransaction(function(err) {
                        callback(err);
                    });
                },

                //查询订单信息
                function (callback) {
                    getOrderInfo(data, connection, callback);
                },

                //修改机构审核状态
                function (callback) {
                    updateMechanism(data, connection, callback);
                },

                //修改订单状态
                function (data, callback) {
                    updateOrderStatus(data, connection, callback);
                },

                //增加权限
                function (data, callback) {
                    addAuth(data, connection, callback);
                },

                //记录日志
                function (data, callback) {
                    log(data, connection, callback);
                }

            ],function(DbErr, isSuccess, insertId) {
                if(DbErr) {
                    connection.rollback(function () {
                        connection.release();
                        cb(DbErr);
                    });
                } else if(!isSuccess) {
                    connection.rollback( function() {
                        connection.release();
                        cb(insertId);
                    });
                } else {
                    connection.commit(function (e) {
                        if(e) {
                            connection.rollback( function() {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, insertId);
                        }
                    });
                }
            });
        }
    });
}

function getAuthInfo(data, connection, callback) {
    var sql = 'select * from auth where mp_id = ? ';
    connection.query(sql, [data.id], function(err, result) {
        if(err) return callback(err);
        if(result.length == 0 ) return callback('地址信息！');
        data.authInfo = result[0];
        callback(err, data);
    });
}
function renewal(data, connection, callback) {
    var sql = 'update auth set duration = duration + ? where mp_id = ? ';
    connection.query(sql, [data.duration, data.id], function(err) {
        if(err) return callback(err);
        var update = 'update mechanism_position set end_date = DATE_ADD(end_date, INTERVAL ? DAY ) where id = ? ';
        connection.query(update, [data.duration, data.id], function(e) {
            callback(e, data)
        })
    })
}
function renewalLog(data, connection, callback) {
    var log = {};
    log.pi_id = 0;
    log.type = 1;
    log.cost = data.pay_amount;
    log.duration = data.duration;
    log.openid = data.authInfo.openid;
    log.num = 0;
    var sql = 'insert into purchase_log set ? ';
    connection.query(sql, log, function(err){
        callback(err, data);
    });
}
paymentDao.renewal = function(data, cb) {
    if(!data) return cb(new ERR(500));
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
        } else {
            async.waterfall([
                function (callback) {
                    connection.beginTransaction(function(err) {
                        callback(err);
                    });
                },

                //查询续期哪个地址
                function(callback) {
                    getAuthInfo(data, connection, callback);
                },

                //修改auth duration 和 mechanism_position 时间
                function(data, callback) {
                    renewal(data, connection, callback);
                },

                //记录日志
                function(data, callback) {
                    renewalLog(data, connection, callback);
                }

            ],function(DbErr, isSuccess, insertId) {
                if(DbErr) {
                    connection.rollback(function () {
                        connection.release();
                        cb(DbErr);
                    });
                } else if(!isSuccess) {
                    connection.rollback( function() {
                        connection.release();
                        cb(insertId);
                    });
                } else {
                    connection.commit(function (e) {
                        if(e) {
                            connection.rollback( function() {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, insertId);
                        }
                    });
                }
            });
        }
    });
}